<template>
  <div class="upload-file">
    <div class="file-upload">
      <a-button
        icon="upload"
        type="primary"
        @click="visible = true"
        :disabled="disabled"
        >{{ $t("user.verification-code.required111566163") }}</a-button
      >
      <span>{{ $t("breach.steps.step1.content.form.file.canupload") }}</span>
      <a-tooltip placement="right" v-if="tip">
        <template slot="title">
          <span class="tip-content">{{ tip }}</span>
        </template>
        <a-icon type="question-circle" />
      </a-tooltip>
    </div>
    <a-table :columns="columns" :dataSource="listData" :pagination="false">
      <span slot="operate" slot-scope="text, record" class="operates">
        <a-icon
          type="download"
          class="mr-[10px]"
          @click="download(record.url)"
        />
        <a-icon
          class="mr-[10px]"
          type="eye"
          theme="filled"
          @click="reviewFile(record)"
        />
        <a-icon
          type="delete"
          theme="filled"
          @click.stop="delRow('listData', record.Id)"
        />
      </span>
    </a-table>
    <a-modal
      v-model="visible"
      :closable="false"
      dialogClass="uploadfile-modal"
      @ok="uploadFile"
      @cancel="modalClose"
    >
      <a-form>
        <a-form-item
          :label="$t('breach.steps.step1.content.form.file.upload')"
          :required="true"
          :label-col="{ span: lang ? 7 : 11 }"
          :wrapper-col="{ span: 12 }"
          labelAlign="left"
        >
          <a-upload
            :multiple="true"
            :customRequest="handleChange"
            :showUploadList="false"
          >
            <a-button type="link">
              {{ $t("breach.steps.step1.content.form.file.upload.select") }}
            </a-button>
          </a-upload>
        </a-form-item>
        <a-form-item
          :label="$t('breach.steps.step1.content.form.file.describe')"
          :required="true"
        >
          <div class="file" v-for="item in fileList" :key="item.Id">
            <span>{{ item.InfoName }}</span>
            <a-input
              v-model="item.InfoDescribe"
              :placeholder="
                $t('breach.steps.step1.content.form.file.describe.placeholder')
              "
            ></a-input>
            <a-button
              icon="delete"
              type="link"
              @click="delRow('fileList', item.Id)"
            ></a-button>
          </div>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal
      :visible="tipVisible"
      :title="$t('breach.steps.step3.action.new.conform.title.tip')"
      dialogClass="uploadfile-tip-modal"
      @cancel="tipCancel"
    >
      <div class="center-content">
        {{ $t("breach.steps.step1.content.form.file.review") }}
      </div>
      <div slot="footer" class="buttons">
        <a-button type="primary" @click="tipCancel"
          >OK（{{ count }}s）</a-button
        >
      </div>
    </a-modal>
  </div>
</template>

<script>
import axios from "axios";
import storage from "store";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import fileReview from "../fileReview/index.vue";
import { canReviewFileMap } from "@/staticLists/public";
import { deleteFile, getFileList } from "@/api/dataBreach/form";
export default {
  name: "uploadFile",
  components: { fileReview },
  props: {
    tip: {
      type: String,
      default: "",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    breachId: {
      type: Number || undefined,
      default: undefined,
    },
    InfoSupplementId: {
      type: Number || undefined,
      default: undefined,
    },
  },
  data() {
    return {
      visible: false,
      fileList: [],
      columns: [
        {
          title: () =>
            this.$t("breach.steps.step1.content.form.file.table.filename"),
          dataIndex: "InfoName",
          key: "InfoName",
        },
        {
          title: () =>
            this.$t("breach.steps.step1.content.form.file.table.describe"),
          dataIndex: "InfoDescribe",
          key: "InfoDescribe",
        },
        {
          title: () =>
            this.$t("breach.steps.step1.content.form.file.table.creator"),
          dataIndex: "creator",
          key: "creator",
        },
        {
          title: "",
          key: "operate",
          scopedSlots: { customRender: "operate" },
        },
      ],
      listData: [],
      lang: localStorage.getItem("lang").includes("zh-CN"),
      canReviewFileMap,
      tipVisible: false,
      count: 5,
      interval: {},
    };
  },
  watch: {
    breachId: {
      async handler(newVal) {
        if (newVal) {
          this.getFiles();
        }
      },
      immediate: true,
    },
    InfoSupplementId: {
      handler(newVal) {
        if (newVal) {
          this.getFiles();
        }
      },
      immediate: true,
    },
  },
  async mounted() {
    let that = this;
    window.addEventListener("setItemEvent", function (e) {
      if (e.key == "lang") {
        that.lang = e.value.includes("zh-CN");
      }
    });
  },
  methods: {
    async handleChange(e) {
      let formdata = new FormData();
      formdata.append("file", e.file);
      try {
        const { status, data } = await axios({
          url: `${process.env.VUE_APP_BASE_API}/v1/oss/upload`,
          method: "post",
          data: formdata,
          headers: {
            token: storage.get(ACCESS_TOKEN),
            tokens: storage.get("bmwToken") || "",
          },
        });
        if (status == 200 && data.code == 1) {
          if (data.data != "") {
            await this.$nextTick();
            var files = data.data;
            if (files != "" && files != undefined) {
              var fileName = files.split("/");
              this.fileList.push({
                Id: +new Date(),
                InfoName: fileName[fileName.length - 1],
                url: data.Url + data.data,
                InfoDescribe: "",
                InfoUrl: data.data,
                creator: this.$store.state.user.info.name,
                ifNew: true,
              });
            }
          }
        } else {
          this.$message.error(
            this.$t("user.verification-code.required111566110577282")
          );
        }
      } catch (error) {
        this.$message.error(
          this.$t("user.verification-code.required111566110577282")
        );
      }
    },
    modalClose() {
      this.visible = false;
      this.fileList = [];
    },
    uploadFile() {
      for (let i = 0; i < this.fileList.length; i++) {
        if (!this.fileList[i].InfoDescribe.trim()) {
          this.$message.error(
            this.$t("breach.steps.step1.content.form.file.describe.placeholder")
          );
          return;
        }
      }
      this.listData = [...this.listData, ...this.fileList];
      this.modalClose();
    },
    async delRow(key, Id) {
      if (key === "listData" && this.breachId) {
        let res = await deleteFile({ Id });
        if (res.code === 1) {
          this[key] = this[key].filter((item) => item.Id !== Id);
        }
      } else {
        this[key] = this[key].filter((item) => item.Id !== Id);
      }
    },
    ifCanReview(url) {
      let list = url.split(".");
      for (const key in this.canReviewFileMap) {
        if (Object.hasOwnProperty.call(this.canReviewFileMap, key)) {
          const element = this.canReviewFileMap[key];
          if (element.includes(list[list.length - 1])) return true;
        }
      }
      return false;
    },
    reviewFile(file) {
      if (this.ifCanReview(file.url)) {
        window.open(`${window.origin}/reviewFile?url=${file.url}`, "_blank");
      } else {
        this.tipVisible = true;
        this.interval = setInterval(() => {
          if (!--this.count) {
            this.tipCancel();
          }
        }, 1000);
      }
    },
    download(url) {
      const a = document.createElement("a");
      a.setAttribute("download", "");
      a.setAttribute("href", url);
      a.click();
    },
    tipCancel() {
      this.tipVisible = false;
      clearInterval(this.interval);
      this.count = 5;
    },
    async getFiles() {
      let { data } = await getFileList({
        page: 1,
        pageSize: 200000,
        BreachId: this.breachId,
        InfoSupplementId: this.InfoSupplementId,
        InfoType: this.InfoSupplementId ? 2 : 1,
      });
      this.listData = data.Lists.map((item) => {
        return {
          ...item,
          creator: item.InfoCreatorStr,
          url: item.InfoUrl,
        };
      });
    },
  },
};
</script>

<style lang="less" scoped>
.upload-file {
  .file-upload {
    display: flex;
    align-items: center;
    & > span {
      margin: 0 10px;
    }
  }
  :deep(.ant-table) {
    .operates i {
      color: #5877a1;
      cursor: pointer;
    }
  }
}
</style>
<style lang="less">
.uploadfile-modal {
  .file {
    display: flex;
    align-items: center;
    & > * {
      flex: 1;
    }
    .ant-btn {
      flex-grow: 0;
      margin-left: 10px;
    }
    span {
      overflow: hidden;
      text-overflow: ellipsis;
      word-break: break-all;
      white-space: nowrap;
      margin-right: 10px;
    }
  }
  .ant-form-item {
    margin-bottom: 0;
  }
}
.uploadfile-tip-modal {
  .center-content {
    width: 100%;
    text-align: center;
    font-weight: 500;
    font-size: 18px;
  }
  .buttons {
    display: flex;
    justify-content: center;
  }
  .ant-modal-header {
    border-bottom: 0;
  }
  .ant-modal-footer {
    border-top: 0;
  }
}
.ant-tooltip {
  max-width: 300px;
  .tip-content {
    display: block;
    width: 280px;
  }
}
</style>